/* Copyright 2008. All rights reserved. */
package org.bling.process;

import java.lang.reflect.Method;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.bling.util.Util;
import org.gorm.orm.GormStandalone;

public class Command  {

    private static final Logger LOG = LogManager.getLogger(Command.class);
    private String controller;
    private String method;
    private String path;
	
    public Command(String path) throws BlingProcessingException {
    	this.path = path;
        controller = "";
        method = "";
        String tokens[] = path.split("/");
        if(tokens.length != 2) {
            throw new BlingProcessingException((new StringBuilder()).append("paths may only be of format 'controller/method'.  Invalid path: '").append(path).append("'").toString());
        } else {
            controller = tokens[0];
            method = tokens[1];
            return;
        }
    }

    public Class getController() throws BlingProcessingException {
        Class klass = null;
        String name = (new StringBuilder()).append(Util.capitalize(controller)).append("Controller").toString();
        try {
            // klass = Class.forName(name);
            klass = GormStandalone.getInstance().getApplication().getClassLoader().loadClass(name);
        } catch(ClassNotFoundException e) {
            throw new BlingProcessingException((new StringBuilder()).append("Could not find controller class ").append(name).toString());
        }
        LOG.debug((new StringBuilder()).append("Controller=").append(klass).toString());
        return klass;
    }

    public String getControllerName() {
    	return controller;
    }
    
    public Method getMethod() throws BlingProcessingException {
        Class klass = getController();
        try {
            return klass.getMethod(method, new Class[0]);
        } catch(SecurityException e) {
            throw new BlingProcessingException((new StringBuilder()).append("Can not execute method ").append(method).append(" on controller ").append(controller).toString());
        } catch(NoSuchMethodException e) {
            throw new BlingProcessingException((new StringBuilder()).append("No Such Method ").append(method).append(" on controller ").append(controller).toString());
        }
    }

    public String getMethodName() { 
    	return method;
    }
    
    public String getPath() {
    	return path;
    }
    
    public String toString() {
    	return path;
    }
}
